package mroute

import (
	"github.com/gin-gonic/gin"
	"mygo/mystruct"
	"mygo/mymongo"
	"path/filepath"
	"encoding/json"
	"fmt"
	"mygo/global"
)

/* =================================================================================
   系统接口
*/
// 修改系统配置
func MySysModel(cont *gin.Context) {
	model := cont.PostForm("model")

	user := mymongo.Get_Chcae_User(cont.GetHeader("UserNameBoot"), global.Mtoken.Key)
	if user == nil {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "没有权限[用户未登录]"})
	}
	if user.Standing <= mystruct.AUTH_Superadmin {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "权限不足"})
		return
	}
	result := &mystruct.Retdate{"MySysModel", mystruct.MyCodeOk, "succeed"}
	switch model {
		case "see":
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": global.Mtoken})

		case "set":
			key   := cont.PostForm("key")
			value := cont.PostForm("value")
			updateConfig := func() error {
				switch key {
					case "key":
						keys, err := mystruct.GenerateAESKey()
						if err != nil {
							return fmt.Errorf("秘钥生成失败: %v", err)
						}
						global.Mtoken.Key = keys
						return nil

					case "sleep":
						global.Mtoken.Sleeptime = mystruct.StrToInt64(value)
						return nil

					case "port":
						global.Mtoken.Port = mystruct.StrToInt64(value)
						return nil

					case "downloadpath":
						if !mystruct.Exists(value) || !mystruct.IsDir(value) {
			            return fmt.Errorf("迁移失败，目录不存在")
			        	}
			        	if value == global.Mtoken.Download_Path {
			            return fmt.Errorf("迁移失败，目录同源")
			        	}
			        	targetDir := filepath.Join(value, "download")
			        	if err := mystruct.Dirmove(global.Mtoken.Download_Path, targetDir); err != nil {
			            return fmt.Errorf("迁移失败: %v", err)
			        	}
			        	global.Mtoken.Download_Path = targetDir
						return nil

					case "logpath":
						if !mystruct.Exists(value) || !mystruct.IsDir(value) {
			            return fmt.Errorf("迁移失败，目录不存在")
			        	}
			        	if value == global.Mtoken.Log_Path {
			            return fmt.Errorf("迁移失败，目录同源")
			        	}
			        	targetDir := filepath.Join(value, "log")
			        	if err := mystruct.Dirmove(global.Mtoken.Log_Path, targetDir); err != nil {
			            return fmt.Errorf("迁移失败: %v", err)
			        	}
			        	global.Mtoken.Log_Path = targetDir
						return nil

					default:
						return fmt.Errorf("不支持的请求参数")
				}
			}
			if err := updateConfig(); err != nil {
			   result.Code = mystruct.MyCodeErr
			   result.Mesg = err.Error()
			} else {
			   if err := mystruct.WriteJSONFile(&global.Mtoken); err != nil {
			      result.Code = mystruct.MyCodeErr
			      result.Mesg = fmt.Sprintf("配置写入失败: %v", err)
			   }
			}
			cont.JSON(mystruct.StatusOK, gin.H{"code": result.Code, "msg": result.Mesg})

		default:
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "参数错误"})
	}
}
// 秘钥操作用户
func MySysKey(cont *gin.Context) {
	if global.Mtoken.Initcode != cont.PostForm("key") {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "秘钥错误"})
		return
	}
	user := &mystruct.Muser{
		Account: "初始秘钥",
		Standing: mystruct.AUTH_ININUSER,
	}
	model := cont.PostForm("model")
	value := cont.PostForm("value")
	account := cont.PostForm("account")
	var json_data map[string]interface{}
	json.Unmarshal([]byte(value), &json_data)

	switch model {
		case "see":
			limit := mystruct.StrToInt64(cont.DefaultPostForm("limit","1000"))
			page  := mystruct.StrToInt64(cont.DefaultPostForm("page","0"))
			_, res := mymongo.List_User(limit, page, json_data, user)
			var map_list []mystruct.Muser
			for _, value := range res {
				if value.Standing > mystruct.AUTH_Administrator {
					map_list = append(map_list, value)
				}
			}
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": map_list})

		case "set":
			ret := mymongo.Set_User(account, json_data, user)
			cont.JSON(mystruct.StatusOK, gin.H{"code": ret.Code, "msg": ret.Mesg})

		case "add":
			password := json_data["password"].(string)
			standing := int64(json_data["standing"].(float64))
			ret := mymongo.Register_User(account, user.Account, password, standing)
			cont.JSON(mystruct.StatusOK, gin.H{"code": ret.Code, "msg": ret.Mesg})

		case "del":
			ret := mymongo.Delete_User(account, user)
			cont.JSON(mystruct.StatusOK, gin.H{"code": ret.Code, "msg": ret.Mesg})

		default:
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": "参数错误"})
	}
}
// 重启关闭
func MySysApi(cont *gin.Context, quit chan int64) {
	model := cont.Query("model")
	user := mymongo.Get_Chcae_User(cont.GetHeader("UserNameBoot"), global.Mtoken.Key)
	if user == nil {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "没有权限[用户未登录]"})
		return
	}
	if user.Standing <= mystruct.AUTH_Superadmin {
		cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "权限不足"})
		return
	}
	switch model {
		case "exit":
			quit <- 1
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": "关闭中..."})

		case "restart":
			quit <- 2
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": "重启中..."})
			
		default:
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "参数错误"})
	}
}